package com.hg.hggood.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.hg.hggood.common.AlipayProperties;
import com.hg.hggood.service.IAlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin(value = "http://localhost:8081")
@RequestMapping("alipay")
@RestController
public class AlipayController extends BaseController{
    @Resource
    private AlipayClient alipayClient;
    @Resource
    private AlipayProperties alipayProperties;
    @Autowired
    private IAlipayService alipayService;

    @RequestMapping("{oid}/pay_wap")
    public String PayWap(@PathVariable("oid") Integer oid,
                         HttpSession session) throws AlipayApiException {
        AlipayTradeWapPayResponse response= alipayClient.pageExecute(
                alipayService.payWap(
                        oid,
                        getuidFromSession(session),
                        getUsernameFromSession(session)));
        return response.getBody();
    }
    @RequestMapping("{oid}/query")
    public AlipayTradeQueryResponse query(@PathVariable("oid") Integer oid,
                                          HttpSession session) throws Exception{
        return alipayService.Query(
                oid,
                getuidFromSession(session),
                //.getTradeStatus()
                getUsernameFromSession(session));
    }

    @RequestMapping("{oid}/pay_page")
    public Serializable payPage(@PathVariable("oid") Integer oid,
                                HttpSession session) throws AlipayApiException {
        AlipayTradePagePayResponse response= alipayClient.pageExecute(
                alipayService.payPage(
                        oid,
                        getuidFromSession(session),
                        getUsernameFromSession(session)));
        return response.getBody();
    }

    @RequestMapping("/close")
    public String close() throws Exception{
        AlipayTradeCloseModel model=new AlipayTradeCloseModel();
        model.setOutTradeNo("2002");

        AlipayTradeCloseRequest request=new AlipayTradeCloseRequest();
        request.setBizModel(model);

        return alipayClient.execute(request).getBody();
    }

    @RequestMapping("/refund")
    public String refund() throws Exception{
        AlipayTradeRefundModel model=new AlipayTradeRefundModel();
        model.setOutTradeNo("529141855345897");
        model.setRefundAmount("10.8");
        model.setOutRequestNo("224");  //分批次退款时，对应的每一次退款请求号，同一订单该值不能相同

        AlipayTradeRefundRequest refundRequest=new AlipayTradeRefundRequest();
        refundRequest.setBizModel(model);

        AlipayTradeRefundResponse refundResponse=alipayClient.execute(refundRequest);

        return "退款总金额："+refundResponse.getRefundFee();
    }

    @RequestMapping("/refund_query")
    public String refundQuery() throws Exception{
        AlipayTradeFastpayRefundQueryModel model=new AlipayTradeFastpayRefundQueryModel();
        model.setOutTradeNo("2002");     //商户订单号
        model.setOutRequestNo("100");    //退款请求号

        AlipayTradeFastpayRefundQueryRequest refundQueryRequest=new AlipayTradeFastpayRefundQueryRequest();
        refundQueryRequest.setBizModel(model);

        AlipayTradeFastpayRefundQueryResponse refundQueryResponse=alipayClient.execute(refundQueryRequest);

        return "本次退款金额为："+refundQueryResponse.getRefundAmount()+
                "\n订单总金额为："+refundQueryResponse.getTotalAmount();
    }

    @RequestMapping("/queryDownload")
    public String downloadUrl() throws Exception{    //对账单下载地址
        AlipayDataDataserviceBillDownloadurlQueryModel model=new AlipayDataDataserviceBillDownloadurlQueryModel();
        model.setBillType("trade");
        model.setBillDate("2020-04-06");

        AlipayDataDataserviceBillDownloadurlQueryRequest request=new AlipayDataDataserviceBillDownloadurlQueryRequest();
        request.setBizModel(model);

        AlipayDataDataserviceBillDownloadurlQueryResponse response=alipayClient.execute(request);

        return response.getBillDownloadUrl();
    }

    @RequestMapping("/notify")
    public void notify(HttpServletRequest request) throws Exception{  //异步通知接口
        if (check(request.getParameterMap())){
            System.out.println("异步通知");
        }else {
            System.out.println("验签失败");
        }
    }

    @RequestMapping("/return")
    public String returnUrl(HttpServletRequest request) throws Exception{ //同步跳转接口
        if (check(request.getParameterMap())){
            return "success";
        }else {
            return "false";
        }
    }

    private boolean check(Map<String,String[]> requestParams) throws Exception{
        Map<String,String> params = new HashMap<>();

        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }

            params.put(name, valueStr);
        }

        return AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(),
                alipayProperties.getCharset(), alipayProperties.getSignType()); //调用SDK验证签名
    }
}
